package edu.cuit.canary.servlet;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/8/2 11:23
 *
 * 在web应用中
 *  1.用html表达信息
 *  2.使用url定位资源
 *  3.使用http协议传输信息
 * ========================servlet需要注册给servlet容器===================
 *  1.xml
 *  2.注解(主流)
 */
public class FirstServlet implements Servlet {
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    /**
     * 每次请求都会调用service方法用于处理客户端的请求
     * @param req 请求对象
     * @param response 响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest req, ServletResponse response) throws ServletException, IOException {
        var request = (HttpServletRequest)req;
        System.out.println("http协议:" + request.getProtocol());
        System.out.println("uri:" + request.getRequestURI());
        System.out.println("url:" + request.getRequestURL());
        System.out.println("request method:" + request.getMethod());

        System.out.println("host:" + request.getRemoteHost());
        System.out.println("client ip:" + request.getRemoteAddr());

        //向客户端进行响应
        PrintWriter writer = response.getWriter();
        // 设置响应头(content-type)告诉浏览器响应的内容类型，封装成了方便方便设置
        response.setContentType("text/html; charset=utf-8");
        writer.println("<html>");
        writer.println("<head>");
        writer.println("<title>我的第一个servlet</title>");
        writer.println("<body>");
        writer.print("<p>当前时间:");
        writer.print(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
        writer.println("</p>");
        writer.println("</body>");
        writer.println("</head>");
        writer.println("</html>");
    }

    @Override
    public String getServletInfo() {
        return "";
    }

    @Override
    public void destroy() {

    }
}
